const toc = require('markdown-toc');

module.exports = (blog)=>{
  let result =  toc(blog.MarkdownContent).json;

  function transfer(arr){
      const stack = [];
      const result = [];
      let min = 6;
      function createTocItem(item) {
          return {
              name: item.content,
              anchor: `article-md-title-${item.i}`,
              lvl: item.lvl,
              children: []
          }
      }
      function handlerItem(item) {
          const top = stack[stack.length - 1];
          if(!top) {
              stack.push(item);
          }else if(item.lvl > top.lvl) {
              top.children.push(item);
              stack.push(item)
          }else {
              stack.pop()
              handlerItem(item)
          }
      }
      for(const i of arr){
          if(i.lvl < min) min = i.lvl
      } 

      for(const item of arr) {
          const tocItem = createTocItem(item)
          if(tocItem.lvl === min) {
              result.push(tocItem)
          }
          handlerItem(tocItem)
      }
      return result;
      
  }
/**
 * [
  { content: '概述', slug: '概述', lvl: 1, i: 0, seen: 0 },
  { content: '简单请求', slug: '简单请求', lvl: 1, i: 1, seen: 0 },
  { content: '简单请求的判定', slug: '简单请求的判定', lvl: 2, i: 2, seen: 0 },
  { content: '简单请求的交互规范', slug: '简单请求的交互规范', lvl: 2, i: 3, seen: 0 },
  { content: '需要预检的请求', slug: '需要预检的请求', lvl: 1, i: 4, seen: 0 },
  { content: '附带身份凭证的请求', slug: '附带身份凭证的请求', lvl: 1, i: 5, seen: 0 },
  { content: '一个额外的补充', slug: '一个额外的补充', lvl: 1, i: 6, seen: 0 }
]

 */
  blog.toch = transfer(result)
  for(const p of result) {
    switch(p.lvl) {
        case 1 : { 
                 const str = `<h1 id="article-md-title-${p.i}">`
                 blog.htmlContent = blog.htmlContent.replace('<h1>',str);
                 break;
        }
        case 2 : { 
                 const str = `<h2 id="article-md-title-${p.i}">`
                 blog.htmlContent = blog.htmlContent.replace('<h2>',str);
                 break;
        }
        case 3 : { 
                 const str = `<h3 id="article-md-title-${p.i}">`
                 blog.htmlContent = blog.htmlContent.replace('<h3>',str);
                 break;
        }
        case 4 : { 
                 const str = `<h4 id="article-md-title-${p.i}">`
                 blog.htmlContent = blog.htmlContent.replace('<h4>',str);
                 break;
        }
        case 5 : { 
                 const str = `<h5 id="article-md-title-${p.i}">`
                 blog.htmlContent = blog.htmlContent.replace('<h5>',str);
                 break;
        }
        case 6 :{ 
                 const str = `<h6 id="article-md-title-${p.i}">`
                 blog.htmlContent = blog.htmlContent.replace('<h6>',str);
                 break;
        }

    }

  }
  delete blog.MarkdownContent

  return blog
}